/**
 * Copyright 2012 ibiblio
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0.txt
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.ibiblio.terasaur.controller

import java.lang.Integer

class ParamsHelper {
    private static MAX_DEFAULT = 10
    private static MAX_LIMIT = 100
    private static OFFSET_DEFAULT = 0

    /**
     * Extract offset and max values from a params map.  Intended for use
     * by controllers that need paging support.  Default and maximum values
     * are applied to prevent someone from fetching all rows for a given
     * entity.
     *
     * Returns Map with offset and max key/value pairs.
     *
     * @param Map params
     * @return Map
     */
    public Map getOffsetMax(Map params) {
        int offset
        int max

        if (params && params.offset) {
            offset = Math.max(0, _stringToInt(params.offset, OFFSET_DEFAULT))
        } else {
            offset = OFFSET_DEFAULT
        }

        if (params && params.max) {
            max = Math.min(_stringToInt(params.max, MAX_DEFAULT), MAX_LIMIT)
            max = Math.max(max, MAX_DEFAULT)
        } else {
            max = MAX_DEFAULT
        }

        return [offset:offset, max:max]
    }

    private Integer _stringToInt(String s, Integer defaultValue) {
        Integer value
        try {
            value = Integer.parseInt(s)
        } catch (NumberFormatException e) {
            value = defaultValue
        }
        return value
    }
}
